package com.lixin.smartclassroom.ui.home.tab2.activity

import android.annotation.SuppressLint
import android.os.Build
import androidx.annotation.RequiresApi
import com.drake.brv.utils.bindingAdapter
import com.drake.channel.receiveEvent
import com.drake.channel.sendEvent
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.drake.tooltip.dialog.BubbleDialog
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.canyushijuan
import com.lixin.smartclassroom.api.outgroup
import com.lixin.smartclassroom.api.qiandao
import com.lixin.smartclassroom.api.xiaojiepaperdetail
import com.lixin.smartclassroom.bean.BaseBean
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.common.saveSuccessDialog
import com.lixin.smartclassroom.databinding.ActivityPracticeDetailBinding
import com.lixin.smartclassroom.ext.chapterPosition
import com.lixin.smartclassroom.ext.child_id
import com.lixin.smartclassroom.ext.user_role
import com.lixin.smartclassroom.ui.home.adapter.teacherLeader
import com.lixin.smartclassroom.ui.home.tab1.activity.CommentDetailAct
import com.lixin.smartclassroom.ui.home.tab1.activity.PracticeAnswerAct
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.commonDialog
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.start
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

/**
 * Description 练习详情
 * Author: lwc
 * Date:2023/12/13 14:18
 */
class PracticeDetailAct : BaseActivity<ActivityPracticeDetailBinding>() {
    override fun getViewBinding() = ActivityPracticeDetailBinding.inflate(layoutInflater)

    override fun topBarHide() = false
    override fun startPadding() = true
    private lateinit var listBean: ArrayList<DataListBean>
    override fun title() = "详情"
    private var practiceType = ""//1常规题  2评价题  3签到
    private var smallid = ""
    private var ifzt = ""
    private var paperId = ""
    private var paperBean: BaseBean? = null
    private var evaluateStartFlag = false


    @RequiresApi(Build.VERSION_CODES.O)
    override fun iniView() {

        practiceType = getIntentString("type")
        smallid = getIntentString("samllid")
        ifzt = getIntentString("ifzt")

        listBean = ArrayList()
        binding.apply {
            when (practiceType) {
                "1" -> {

                }

                "2" -> {
                    llScore.gone()
                    llGroup.gone()
                    llTmsl.gone()
                    divider.gone()
                }

                "3" -> {
                    llScore.gone()
                    divider.gone()
                    llGroup.visible()
                    rlSign.visible()
                    llAttend.gone()
                    initThread()
                }
            }

            when (user_role) {
                1 -> {
                    binding.btnPractice.text = "查看我的学生"
                    binding.llGroup.gone()
                }

                2 -> {
                    when (ifzt) {
                        "2" -> {
                            binding.btnPractice.text = "查看答案"
                            binding.btnStart.text = "查看答案"
                        }

                        else -> binding.btnPractice.text = "去练习"
                    }

                }
            }

        }

        getPaperDetail()
        getCanyuData()

        receiveEvent<String>("refreshGroupMessage") {
            getPaperDetail()
        }

    }

    private fun getCanyuData() {
        binding.recycler.teacherLeader(2).apply {
            R.id.rl.onClick {
                start(CommentDetailAct::class.java) {
                    putExtra("type", (getModel(modelPosition) as DataListBean).type)
                    putExtra("id", (models?.get(modelPosition) as DataListBean).id)
                    putExtra("xiaojieid", smallid)
                }
            }
        }
        scopeNetLife {
            binding.apply {
                refresh.onRefresh {
                    val bubbleDialog = BubbleDialog(this@PracticeDetailAct)
                    scopeDialog(bubbleDialog) {
                        listBean = when (user_role) {
                            1 -> canyushijuan(index, 10, smallid, child_id)!!
                            else -> canyushijuan(index, 10, smallid)!!
                        }

                        addData(listBean) {
                            if (binding.recycler.bindingAdapter.models?.size == 0) {
                                binding.state.showEmpty()
                                binding.recycler.gone()
                            } else {
                                binding.recycler.visible()
                            }
                            listBean.size == 10
                        }
                    }
                }.autoRefresh()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun getPaperDetail() {
        binding.apply {
            scopeNetLife {
                paperBean = xiaojiepaperdetail(smallid)
                if (paperBean!!.result == "0") {
                    paperId = paperBean!!.paperid.toString()
                    tvCyrs.text = paperBean!!.dtstudentcount + "/" + paperBean!!.studentcount
                    tvScore.text = paperBean!!.pingjun
                    tvTitle.text = paperBean!!.title
                    tvTime.text = "发布时间：" + paperBean!!.fabutime

                    tvTmsl.text = paperBean!!.timucount


                    if (user_role == 2) {
                        if (paperBean!!.ifzudui == "1" && paperBean!!.cid?.isEmpty() == true) {
                            llGroup.visible()
                            tvGroupCount.text =
                                "当前任务为小组任务  需人数：" + paperBean!!.peoplecount
                            tvMakeGroup.text = "请先组队"
                            btnMakeGroup.text = "去组队"
                            btnMakeGroup.background = getDrawable(R.drawable.shape_btn_main_27dp)

                        } else if (paperBean!!.ifzudui == "1" && paperBean!!.cid?.isEmpty() != true) {
                            llGroup.visible()
                            tvGroupCount.text = "当前所在小组：" + paperBean!!.groupname
                            tvMakeGroup.text = "组员:" + paperBean!!.groupcustomer
                            btnMakeGroup.text = "退出该队"
                            btnMakeGroup.background = getDrawable(R.drawable.shape_btn_ff7073_27dp)
                        } else {
                            llGroup.gone()
                        }
                    }
                }
            }
        }
    }

    override fun onClick() {
        binding.apply {
            btnMakeGroup.onClick {
                if (paperBean!!.ifzudui == "1" && paperBean!!.cid?.isEmpty() == true) {
                    start(MakeGroupAct::class.java) {
                        putExtra("xiaojieid", smallid)
                        putExtra("peoplecount", paperBean!!.peoplecount)
                    }
                } else {
                    scopeNetLife {
                        val baseBean = outgroup(paperBean!!.cid!!)
                        if (baseBean.result == "0") {
                            saveSuccessDialog("退出小组成功")
                            getPaperDetail()
                        }

                    }
                }
            }

            btnPractice.onClick {
                when (user_role) {
                    1 -> {
                        if (paperBean!!.timucount?.toInt()!! > 0) {
                            for (i in 0 until listBean.size) {

                                if (listBean[i].type == "1") {
                                    start(CommentDetailAct::class.java) {
                                        putExtra("type", "1")
                                        putExtra(
                                            "id",
                                            (binding.recycler.bindingAdapter.models?.get(0) as DataListBean).id
                                        )
                                        putExtra("xiaojieid", smallid)
                                    }
                                    return@onClick
                                }
                            }
                        }
                    }

                    2 -> {
                        if (paperBean!!.timucount?.toInt()!! > 0) {
                            when (practiceType) {
                                "1" -> {
                                    if (ifzt == "1") {
                                        if (paperBean!!.ifzudui == "1" && paperBean!!.cid!!.isEmpty()) {
                                            commonDialog(
                                                "设置分组",
                                                "当前任务需要" + paperBean!!.peoplecount + "人组队进行",
                                                "已有队伍",
                                                "去组队",
                                                onCancel = {
//                                                    start(PracticeAnswerAct::class.java) {
//                                                        putExtra("questionType", practiceType)
//                                                        putExtra("xiaojieid", smallid)
//                                                        putExtra("ifzt", ifzt)
//                                                    }
                                                    toast("无组队信息，请组队后练习")
                                                },
                                                onSure = {
                                                    start(MakeGroupAct::class.java) {
                                                        putExtra("xiaojieid", smallid)
                                                        putExtra(
                                                            "peoplecount",
                                                            paperBean!!.peoplecount
                                                        )
                                                    }
                                                })
                                        } else {
                                            start(PracticeAnswerAct::class.java) {
                                                putExtra("questionType", practiceType)
                                                putExtra("xiaojieid", smallid)
                                                putExtra("ifzt", ifzt)
                                            }
                                        }
                                    } else {
                                        for (i in 0 until listBean.size) {
                                            if (listBean[i].type == "1") {
                                                start(CommentDetailAct::class.java) {
                                                    putExtra("type", "1")
                                                    putExtra(
                                                        "id",
                                                        (binding.recycler.bindingAdapter.models?.get(
                                                            0
                                                        ) as DataListBean).id
                                                    )
                                                    putExtra("xiaojieid", smallid)
                                                }
                                                return@onClick
                                            }
                                        }
                                    }

                                }

                                "2" -> {
                                    llCyrs.gone()
                                    llScore.gone()
                                    llGroup.gone()
                                    llTmsl.visible()
                                    llAttend.gone()
                                    btnStart.visible()
                                    evaluateStartFlag = true

                                }
                            }
                        } else {
                            toast("题目异常，请联系老师处理")
                        }
                    }
                }
            }

            btnStart.onClick {
                if (ifzt == "1") {
                    if (paperBean!!.ifzudui == "1" && paperBean!!.cid!!.isEmpty()) {
                        commonDialog(
                            "设置分组",
                            "当前任务需要" + paperBean!!.peoplecount + "人组队进行",
                            "已有队伍",
                            "去组队",
                            onCancel = {
//                                start(PracticeAnswerAct::class.java) {
//                                    putExtra("questionType", practiceType)
//                                    putExtra("xiaojieid", smallid)
//                                    putExtra("ifzt", ifzt)
//                                }
                                toast("无组队信息，请组队后练习")
                            },
                            onSure = {
                                start(MakeGroupAct::class.java) {
                                    putExtra("xiaojieid", smallid)
                                    putExtra("peoplecount", paperBean!!.peoplecount)
                                }
                            })
                    } else {
                        start(PracticeAnswerAct::class.java) {
                            putExtra("questionType", practiceType)
                            putExtra("xiaojieid", smallid)
                            putExtra("ifzt", ifzt)
                        }
                    }
                } else {
                    for (i in 0 until listBean.size) {
                        if (listBean[i].type == "1") {
                            start(CommentDetailAct::class.java) {
                                putExtra("type", "1")
                                putExtra(
                                    "id",
                                    (binding.recycler.bindingAdapter.models?.get(0) as DataListBean).id
                                )
                                putExtra("xiaojieid", smallid)
                            }
                            return@onClick
                        }
                    }
                }

            }
            rlSign.onClick {
                scopeNetLife {
                    if (paperBean!!.ifzudui == "1" && paperBean!!.cid?.isEmpty() == true) {
                        commonDialog(
                            "设置分组",
                            "当前任务需要" + paperBean!!.peoplecount + "人组队进行",
                            "已有队伍",
                            "去组队",
                            onCancel = {
                                toast("无组队信息，请组队后练习")
//                                scopeNetLife {
//                                    qiandao(smallid, paperBean?.cid!!)
//                                    tvSign.text = "已签到"
//                                    tvNowTime.gone()
//                                    sendEvent("cs", "refreshDaGang")
//                                    if (thread != null) {
//                                        thread = null
//                                    }
//                                }
                            },
                            onSure = {
                                start(MakeGroupAct::class.java) {
                                    putExtra("xiaojieid", smallid)
                                    putExtra("peoplecount", paperBean!!.peoplecount)
                                }
                            })
                    } else {
                        qiandao(smallid, paperBean?.cid!!)
                        tvSign.text = "已签到"
                        tvCyrs.text = (paperBean!!.dtstudentcount?.toInt()
                            ?.plus(1)).toString() + "/" + paperBean!!.studentcount
                        tvNowTime.gone()
                        sendEvent("cs", "refreshDaGang")
                        if (thread != null) {
                            thread = null
                        }
                    }
                }
            }

        }
    }

    /**
     * 获取当前时间
     */
    @RequiresApi(Build.VERSION_CODES.O)
    fun getCurrentTime(): String {
        val current = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern("HH:mm:ss")
        val formatted = current.format(formatter)
        binding.tvNowTime.text = formatted.toString()
        return formatted.toString()
    }

    /**
     * 启动线程，每一秒更改一次时间
     */

    private var thread: Thread? = null

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initThread() {
        thread = Thread(Runnable {
            try {
                while (true) {
                    Thread.sleep(1000)
                    runOnUiThread {
                        getCurrentTime()
                    }
                }
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        })
        thread!!.start()
    }

}